 using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Text;

namespace SinaWeiboPlugin
{
    class SinaTHelper
    {
        const string _imagePath = @"c:\snapshot.png";
        const string _key = "XXXXXXXX";

        const string _uploadUrl = "http://api.t.sina.com.cn/statuses/upload.xml";
        const string _updateUrl = "http://api.t.sina.com.cn/statuses/update.xml";

        internal bool Upload(TweetBuilder builder)
        {
            return Upload(builder.Message, builder.Snap, builder.UserName, builder.Password);
        }

        internal bool Upload(String message, Image image,String userName,String password)
        {
            HttpWebRequest httpRequest = WebRequest.Create(_uploadUrl) as HttpWebRequest;
            SetCredentials(userName, password, httpRequest);
            httpRequest.Method = "POST";
            httpRequest.Proxy = null;
            httpRequest.KeepAlive = true;
            using(MultiPartBuilder builder = new MultiPartBuilder())
            {
                httpRequest.ContentType = "multipart/form-data; boundary=" + builder.Boundary;
                builder.Append("source",_key);
                builder.Append("status",message);
                byte[] imageBytes = GetImageBytes(image);
                builder.Append("pic",imageBytes,_imagePath,"image/x-png");
                builder.End();

                byte[] result = builder.Result;
                httpRequest.ContentLength = result.Length;
                using(Stream requestStream = httpRequest.GetRequestStream())
                {
                    requestStream.Write(result, 0, result.Length);
                }
            }
            return GetResponse(httpRequest);
        }

        internal bool Update(TweetBuilder builder)
        {
            return Update(builder.Message, builder.UserName, builder.Password);
        }

        internal bool Update(String message, String userName, String password)
        {
            HttpWebRequest httpRequest = WebRequest.Create(_updateUrl) as HttpWebRequest;
            SetCredentials(userName, password, httpRequest);

            httpRequest.Method = "POST";
            httpRequest.Proxy = null;
            httpRequest.ContentType = "application/x-www-form-urlencoded";
            string data = String.Format("source={0}&status={1}", _key, System.Web.HttpUtility.UrlEncode(message));
            byte[] bytesToPost = Encoding.ASCII.GetBytes(data);
            using(Stream requestStream = httpRequest.GetRequestStream())
            {
                requestStream.Write(bytesToPost, 0, bytesToPost.Length);
                requestStream.Close();
            }
            return GetResponse(httpRequest);
        }

        private bool GetResponse(HttpWebRequest httpRequest)
        {
            using (var response = (HttpWebResponse)httpRequest.GetResponse())
            {
                String responseFromServer = response.StatusDescription;
                if (responseFromServer == "OK")
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        private byte[] GetImageBytes(Image image)
        {
            using(MemoryStream imageStream = new MemoryStream())
            {
                image.Save(imageStream, ImageFormat.Png);
                return imageStream.ToArray();
            }
        }

        private void SetCredentials(String username, String password, HttpWebRequest request)
        {
            if(String.IsNullOrEmpty(username) || String.IsNullOrEmpty(password))
            {
                throw new Exception("用户名或密码未设置。");
            }
            else
            {
                String usernamePassword = username + ":" + password;
                CredentialCache myCache = new System.Net.CredentialCache();
                myCache.Add(new Uri(request.RequestUri.AbsoluteUri), "Basic", new System.Net.NetworkCredential(username, password));
                request.Credentials = myCache;
                request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(new UTF8Encoding().GetBytes(usernamePassword)));
            }
        }
    }
}
